# -*- coding: utf-8 -*-
class SaleTypeController < ApplicationController

  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:newSaleType,:editSaleType,:saleTypeLock]

  def saleTypeList

  end

  def create
    begin
      saleType = SaleType.new
      saleType.company_id =  session[:company_id]
      saleType.department_id =  session[:department_id]
      saleType.employee_id =  session[:employee_id]
      saleType.name = params[:name]
      saleType.ab = params[:ab]
      saleType.discount = params[:discount]
      saleType.payment_propotion = params[:payment_propotion]
      saleType.description = params[:description]
      saleType.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end

    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def update
    begin
      saleType = SaleType.find(params[:id])
      saleType.employee_id =  session[:employee_id]
      saleType.department_id =  session[:department_id]
      saleType.name = params[:name]
      saleType.ab = params[:ab]
      saleType.discount = params[:discount]
      saleType.payment_propotion = params[:payment_propotion]
      saleType.description = params[:description]
      saleType.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end

    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #锁定或解锁销售类型
  def saleTypeLock
    saleType = SaleType.find(params[:id])
    if saleType.is_locked == 1
      saleType.is_locked = 0
    else
      saleType.is_locked = 1
    end
    saleType.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getAllSaleTypes
    forCBB = params[:for_cbb]
    if forCBB == 'true'
      saleTypes = SaleType.find(:all,:conditions=>["is_locked = ?",0])
    else
      saleTypes = SaleType.find(:all)
    end
    
    jsonStr="{totalProperty:"+saleTypes.length.to_s+",root:"+saleTypes.to_json(:include=>{:employee=>{:only=>[:id,:name]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getSaleTypeById
    saleType = SaleType.find(params[:id])
    rootStr = saleType.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
end
